let express=require('express')
let mysql = require('mysql')
let app = express()
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({extended: false})); app.use(bodyParser.json())
let db=mysql.createConnection({
    host: 'localhost',
    port: '3306',
    user: 'root',
    password:'',
    database:'exam'
})
db.connect()

// 注册
app.post('/register',(req,res)=>{
	let info=req.body
	db.query('SELECT * FROM register', (err, result) => {
		if (err) throw err;
	let boo= result.some(item=>{
			return item.schoolNum==info.schoolNum
		})
		if(!boo){
		 let sql="INSERT INTO register SET ?"
		  db.query(sql,info,(error, results)=>{
				if (error) {throw error}
				res.send(true)
			})
		}else{
			res.send(false)
		}
	})
})
// 登录
app.post('/login',(req,res)=>{
	let {schoolNum,password}=req.body
	db.query('SELECT * FROM register', (err, result) => {
			if (err) throw err;
			let boo= result.some(item=>{
				return item.schoolNum==schoolNum&&item.password==password
			})
			if(boo){
				res.send(true)
			}else{
				res.send(false)
			}
	})
})
// 老师出题
app.post('/submitTitle',(req,res)=>{
	let obj=req.body
	console.log(obj)
	// // 查询题库是否存在相同题目
	db.query('SELECT * FROM questions', (err, result) => {
		let boo= result.some(item=>{
			return item.title==obj.topic
		})
		// 不存在则加入题库
		if(!boo){
			let sql="INSERT INTO questions SET ?"
			db.query(sql,obj,(err,result)=>{
				if (err) throw err;
				res.send(true)
			})
		}else{
			res.send(false)
		}
	})
})
// 当前试卷
let examPaper=[]
//生成试卷
app.get('/examPaper', (req, res) => {
	 examPaper = []
	let obj = req.query
	db.query(`select * from questions where subject="${obj.subject}" and chapter="第一章" 
	order by rand() limit ${obj.first}`, (err, result1) => {
			// examPaper.push(result1)
			db.query(`select * from questions where subject="${obj.subject}" and chapter="第二章" 
	order by rand() limit ${obj.second}`, (err, result2) => {
					// examPaper.push(result2)
					db.query(`select * from questions where subject="${obj.subject}" and chapter="第三章" 
	order by rand() limit ${obj.third}`, (err, result3) => {
							examPaper=[...result1,...result2,...result3]
							console.log(examPaper)
						})
				})
	})
})

// 设置后台时间戳
let time = 0

// 获取题目
app.get('/getTitle',(req,res)=>{
	console.log(examPaper)
	if(req.query.time){
		time=req.query.time
	}
	res.send({examPaper,time})
})
app.listen(3001)